package com.course.auth;

import com.course.util.AuthUtils;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Justin on 2017/5/30.
 */
@Component
public class JwtAuthFilter extends OncePerRequestFilter {

    private static final String TOKEN_PREFIX = "Bearer ";
    private static final String TOKEN_HEADER = "Authorization";

    private final UserDetailsService userDetailsService;

    @Autowired
    public JwtAuthFilter(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        try {
            String header = request.getHeader(TOKEN_HEADER);
            if (header != null && header.startsWith(TOKEN_PREFIX)) {
                final String jwt = header.substring(TOKEN_PREFIX.length());
                String username = AuthUtils.parseToken(jwt);
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                Authentication token = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(token);
            }
        } catch (ExpiredJwtException e) {
            response.sendError(403, "TokenExpired");
            return;
        } catch (Exception e) {
            response.sendError(403, "TokenError");
            return;
        }
        chain.doFilter(request, response);
    }
}
